<template>
  <view class="review">
    <!-- 导航栏 -->
    <NavBar title="评价商品" />

    <!-- 商品信息 -->
    <view class="goods-section">
      <view class="goods-list">
        <view class="goods-item" v-for="(item, index) in orderGoods" :key="index">
          <image :src="item.goods.cover" class="goods-image" />
          <view class="goods-info">
            <text class="goods-name">{{ item.goods.title }}</text>
            <text class="goods-sku" v-if="item.skuText">{{ item.skuText }}</text>
            <view class="goods-price-qty">
              <nut-price :price="item.price" size="normal" />
              <text class="goods-qty">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 评价表单 -->
    <view class="review-form">
      <!-- 评分 -->
      <view class="form-item">
        <view class="form-label">商品评分</view>
        <view class="form-content">
          <nut-rate v-model="rating" size="22" active-color="#fa2c19" />
          <text class="rating-text">{{ getRatingText(rating) }}</text>
        </view>
      </view>

      <!-- 评价内容 -->
      <view class="form-item">
        <view class="form-label">评价内容</view>
        <view class="form-content">
          <textarea
            v-model="content"
            class="review-textarea"
            placeholder="请分享您对商品的使用体验和感受..."
            maxlength="500"
          />
          <view class="textarea-counter">{{ content.length }}/500</view>
        </view>
      </view>

      <!-- 上传图片 -->
      <view class="form-item">
        <view class="form-label">上传图片 <text class="optional">(选填)</text></view>
        <view class="form-content">
          <nut-uploader
            v-model:file-list="uploadImages"
            url="/api/upload"
            maximum="6"
            multiple
            @success="onUploadSuccess"
          >
            <template #default>
              <view class="upload-trigger">
                <Photograph size="20px" />
                <text>上传图片</text>
              </view>
            </template>
          </nut-uploader>
          <view class="upload-tips">最多上传6张图片</view>
        </view>
      </view>

      <!-- 匿名评价 -->
      <view class="form-item">
        <view class="form-label">匿名评价</view>
        <view class="form-content">
          <nut-switch v-model="isAnonymous" />
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-action">
      <nut-button type="primary" block @click="submitReview" :disabled="!canSubmit">提交评价</nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '../../components/NavBar/index.vue'
import orderApi from '../../api/order'
import { Photograph } from '@nutui/icons-vue-taro'

// 获取订单ID
const orderId = Taro.getCurrentInstance().router?.params.id

// 订单商品信息
const orderGoods = ref([])

// 评价表单数据
const rating = ref(5) // 默认5星
const content = ref('')
const uploadImages = ref([])
const isAnonymous = ref(false)

// 获取评分文字描述
const getRatingText = (score: number) => {
  const texts = ['很差', '较差', '一般', '不错', '很好']
  return texts[score - 1] || '很好'
}

// 是否可以提交
const canSubmit = computed(() => {
  return rating.value > 0 && content.value.trim().length > 0
})

// 获取订单商品信息
const fetchOrderGoods = () => {
  if (!orderId) return
  
  orderApi.getOrderDetail(orderId).then(res => {
    orderGoods.value = res.data.goods
  }).catch(err => {
    Taro.showToast({
      title: err.message || '获取订单信息失败',
      icon: 'none'
    })
  })
}

// 上传成功回调
const onUploadSuccess = (response: any, file: any) => {
  // 实际应用中，这里应该处理服务器返回的图片URL
  console.log('上传成功', response, file)
}

// 提交评价
const submitReview = () => {
  if (!orderId) return
  if (!canSubmit.value) return
  
  Taro.showLoading({ title: '提交中...' })
  
  // 获取上传的图片URL列表
  const imageUrls = uploadImages.value
    .filter(file => file.status === 'success')
    .map(file => file.url || '')
  
  // 遍历商品，提交每个商品的评价
  const promises = orderGoods.value.map(item => {
    return orderApi.reviewOrder(orderId, {
      goodsId: item.goods.id,
      rating: rating.value,
      content: content.value,
      images: imageUrls,
      isAnonymous: isAnonymous.value
    })
  })
  
  Promise.all(promises)
    .then(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '评价成功',
        icon: 'success'
      })
      
      // 延迟返回订单详情页
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    })
    .catch(err => {
      Taro.hideLoading()
      Taro.showToast({
        title: err.message || '评价失败',
        icon: 'none'
      })
    })
}

// 页面加载
onMounted(() => {
  fetchOrderGoods()
})
</script>

<style lang="scss">
.review {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.goods-section {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
  
  .goods-list {
    .goods-item {
      display: flex;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .goods-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
        flex-shrink: 0;
      }
      
      .goods-info {
        flex: 1;
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        .goods-name {
          font-size: 14px;
          line-height: 1.4;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .goods-sku {
          font-size: 12px;
          color: #999;
          margin: 4px 0;
        }
        
        .goods-price-qty {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .goods-qty {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}

.review-form {
  background-color: #fff;
  padding: 16px;
  
  .form-item {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .form-label {
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #333;
      
      .optional {
        font-size: 12px;
        color: #999;
        font-weight: normal;
      }
    }
    
    .form-content {
      .rating-text {
        font-size: 14px;
        color: #fa2c19;
        margin-left: 10px;
      }
      
      .review-textarea {
        width: 100%;
        height: 120px;
        padding: 10px;
        border: 1px solid #eee;
        border-radius: 4px;
        font-size: 14px;
        line-height: 1.5;
        box-sizing: border-box;
      }
      
      .textarea-counter {
        text-align: right;
        font-size: 12px;
        color: #999;
        margin-top: 5px;
      }
      
      .upload-trigger {
        width: 80px;
        height: 80px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border: 1px dashed #ddd;
        border-radius: 4px;
        color: #999;
        
        text {
          font-size: 12px;
          margin-top: 5px;
        }
      }
      
      .upload-tips {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
      }
    }
  }
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 16px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}
</style>